from baseview import BaseView
from ..bases import widgets
from .. import editors
from ..childgroup_list import ChildGroupList

class GlobalAttributesView(BaseView):
    topwidget_name = 'Global Attributes Editor'
    topwidget_cls = widgets.HPane
    def __init__(self, **kwargs):
        self.topwidget = widgets.VBox()
        super(GlobalAttributesView, self).__init__(**kwargs)
        self.DeviceSystem = self.MainController.DeviceSystem
        
        self.attribute_editor = None
        
        frame = self.make_child_widget(widgets.Frame, 'frame1', label='Attributes')
        col_names = ['id', 'Name']
        col_attrs = ['id', 'name']
        list_types = [str, str]
        alkwargs = dict(name='Global Attributes', 
                        child_group=self.DeviceSystem.GlobalAttributes, 
                        col_names=['id', 'Name'], 
                        col_attrs=['id', 'name'], 
                        list_types=[str, str])
        self.attributes_list = self.add_editor(ChildGroupList, **alkwargs)
        self.attributes_list.bind(current_child=self.on_attributes_list_current_child_set)
        
        frame.pack_start(self.attributes_list.topwidget, expand=True)
        
        hbox = widgets.HBox()
        d = {'btnNewAttrib':'New Attribute', 'btnDelAttrib':'Delete'}
        for k, v in d.iteritems():
            btn = self.make_child_widget(widgets.Button, k, label=v)
            btn.connect('clicked', self.on_attribute_list_btns_clicked, k)
            hbox.pack_start(btn)
        frame.pack_start(hbox)
        
        self.topcontainer.pack_start(frame)
        
        self.topwidget.show_all()
        
    def on_attributes_list_current_child_set(self, **kwargs):
        attrib = kwargs.get('value')
        self.set_current_attribute(attrib)
    
    def set_current_attribute(self, obj):
        if self.attribute_editor is not None:
            self.remove_editor(self.attribute_editor)
        if obj is None:
            return
        self.add_editor(editors.AttributeEditor, 'attribute_editor', attribute=obj)
        self.topcontainer.pack_start(self.attribute_editor.topwidget)
        
    def on_attribute_list_btns_clicked(self, btn, key):
        if key == 'btnNewAttrib':
            attrib = self.DeviceSystem.add_global_attribute(name='New Attribute')
            self.attributes_list.current_child = attrib
        elif key == 'btnDelAttrib':
            attrib = self.attributes_list.current_child
            if attrib is not None:
                self.DeviceSystem.del_global_attribute(attribute=attrib)
        
